const async = require('async');
const services = require('../../services');
const enums = require('../../enums');

const commonService = services.common;
const eLancoService = services.eLanco;

module.exports = (req, res, callback) => {
  const id = req.params.id == 0 ? null : req.params.id;
  const formId = req.body.formId;
  const data = req.body.formDetail;
  const { WfRunInstance: formDetailModel } = commonService.getModels();
  const getForm = (next) => {
    eLancoService.getFormIncludeAll(formId, next);
  };
  const saveFormDetail = (form, next) => {
    formDetailModel.upsert({
      id,
      formId: form.id,
      flowId: form.flow().id,
      formNumber: eLancoService.getFormNumber(form.formNumber),
      formStatus: enums.formStatus.saved,
      approvalStep: 0,
      formDetail: data,
    }, next);
  };
  async.waterfall([getForm, saveFormDetail], callback);
};
